9537. Transpose the matrix

 

Given matrix A. Transpose it.

Let B be the transposed matrix A. Then Biju = Aji.

Input. The first line contains the size of the matrix n and m (1 n, m 100). Each of the next n lines contains m integers and describe the matrix A.

 

Output. Print the transposed matrix A: m lines, each with n integers.

 

Sample input

Sample output

3 2

1 2

3 4

5 6

1 3 5

2 4 6

 

 

SOLUTION

algebra

 

Algorithm analysis

For a given matrix A, construct a transposed B, where Bij = Aji.

 

Algorithm realization

Declare the input matrix a and the transposed matrix b.

 

#define MAX 100

int a[MAX][MAX], b[MAX][MAX];

 

Read the input data.

 

scanf("%d %d", &n, &m);

for (i = 0; i < n; i++)

for (j = 0; j < m; j++)

  scanf("%d", &a[i][j]);

 

Construct a transposed matrix.

 

for (i = 0; i < n; i++)

for (j = 0; j < m; j++)

  b[j][i] = a[i][j];

 

Print a transposed matrix.

 

for (i = 0; i < m; i++)

{

  for (j = 0; j < n; j++)

    printf("%d ", b[i][j]);

  printf("\n");

}

 

Algorithm realization – double pointer

 

#include <stdio.h>

 

int i, j, n, m;

int **a, **b;

 

void Read(int **&matr, int n, int m)

{

  matr = new int*[n];

  for (i = 0; i < n; i++)

  {

    matr[i] = new int[m];

    for (j = 0; j < m; j++)

      scanf("%d", &matr[i][j]);

  }

}

 

int ** Transpose(int ** a, int n, int m)

{

  int **b = new int*[m];

  for (i = 0; i < m; i++)

    b[i] = new int[n];

 

  for (i = 0; i < m; i++)

  for (j = 0; j < n; j++)

    b[i][j] = a[j][i];

 

  return b;

}

 

void Print(int **a, int n, int m)

{

  for (i = 0; i < n; i++)

  {

    for (j = 0; j < m; j++)

      printf("%d ", a[i][j]);

    printf("\n");

  }

}

 

int main(void)

{

  scanf("%d %d", &n, &m);

  Read(a, n, m);

 

  b = Transpose(a, n, m);

  Print(b, m, n);

 

  return 0;

}

 

Algorithm realization – double pointer + file

 

#include <stdio.h>

 

int i, j, n, m;

int **a, **b;

FILE *in, *out;

 

void Read(int **&matr, int n, int m)

{

  matr = new int*[n];

  for (i = 0; i < n; i++)

  {

    matr[i] = new int[m];

    for (j = 0; j < m; j++)

      fscanf(in, "%d", &matr[i][j]);

}

}

 

void Transpose(int ** a, int **&b, int n, int m)

{

  b = new int*[m];

  for (i = 0; i < m; i++)

    b[i] = new int[n];

 

  for (i = 0; i < m; i++)

  for (j = 0; j < n; j++)

    b[i][j] = a[j][i];

}

 

void Print(int **a, int n, int m)

{

  for (i = 0; i < n; i++)

  {

    for (j = 0; j < m; j++)

      fprintf(out, "%d ", a[i][j]);

    fprintf(out, "\n");

  }

}

 

int main(void)

{

  in = fopen("input.txt", "r"); // r - read

  out = fopen("output.txt", "w"); // w - write

 

  fscanf(in, "%d %d", &n, &m);

  Read(a, n, m);

 

  Transpose(a, b, n, m);

  Print(b, m, n);

 

  return 0;

}